﻿#include "EnableSwitchDelegate.h"


#define BUTTON_WIDTH 45
#define BUTTON_HEIGHT 20


EnableSwitchDelegate::EnableSwitchDelegate(QObject* parent)
	:QStyledItemDelegate(parent)
{

}

void EnableSwitchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	painter->save();
	painter->setRenderHint(QPainter::RenderHint::Antialiasing);			//让绘制的图形和文本边缘更加平滑

	auto enable = index.data(Qt::UserRole).toBool();
	//qDebug() << enable;

	QString text = enable ? "正常" : "禁用";

	//绘制文本：
	if (enable)
	{
		painter->setPen(QColor(Qt::green));
	}
	else
	{
		painter->setPen(QColor(Qt::red));
	}

	//文字大小：
	int fontwidth = painter->fontMetrics().horizontalAdvance(text);
	int fontheight = painter->fontMetrics().height();

	//文本+按钮整体居中计算：
	int h_space = (option.rect.width() - (fontwidth + BUTTON_WIDTH)) / 2;
	int v_sapce = (option.rect.height() - fontheight) / 2;

	painter->drawText(QPoint(option.rect.x() + h_space,option.rect.bottom() - v_sapce - 2), text);


	//绘制按钮：
	QRect btnRect = { option.rect.x() + h_space + fontwidth + 10,option.rect.y() + (option.rect.height() - BUTTON_HEIGHT)/2,BUTTON_WIDTH,BUTTON_HEIGHT};
	//绘制圆角矩形：
	painter->setBrush(enable?QColor(97,162,243) :QColor(136,136,138));				//设置矩形填充色
	painter->setPen(QColor(Qt::gray));						//设置矩形边框色
	painter->drawRoundedRect(btnRect, btnRect.height() / 2, btnRect.height() / 2);


	//绘制按钮中的小球：
	if (option.state & QStyle::State_MouseOver && btnRect.contains(mousepos))				//鼠标悬停到此处
	{
		painter->setBrush(QColor(232, 232, 232));
	}
	else																					//正常显示
	{
		painter->setBrush(QColor(Qt::white));				//设置小球填充色
	}
	painter->setPen(Qt::NoPen);							//不绘制小球边框


	//如果是真，就表明用户状态是正常的，把小球绘制在圆角矩形的右侧：
	if (enable)
	{
		painter->drawEllipse(btnRect.right() - 20, btnRect.y(), 20, 20);
	}
	//假的，就说明是禁用状态，绘制在圆角矩形的左侧：
	else
	{
		painter->drawEllipse(btnRect.x(), btnRect.y(), 20, 20);
	}


	painter->restore();
}

bool EnableSwitchDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
	//鼠标点击该项，改变用户状态：
	if (event->type() == QEvent::MouseButtonRelease)
	{
		auto enable = model->data(index, Qt::UserRole).toBool();
		model->setData(index, !enable,Qt::UserRole);

		//发送数据信息：
		emit enableswdeleData(!enable, index);
	}
	else if (event->type() == QEvent::MouseMove)
	{
		auto ev = dynamic_cast<QMouseEvent*> (event);
		mousepos = ev->position().toPoint();
		//qDebug() << mousepos;


		auto view = dynamic_cast<QAbstractItemView*>(parent());
		if (view)
		{
			view->viewport()->update(option.rect);
		}

	}


	return QStyledItemDelegate::editorEvent(event,model,option,index);
}
